<script setup>

import router from "@/router/index.js";
import {sendPhoneCodeAPI, userRegisterAPI} from "@/apis/user.js";
import {ElMessage, ElMessageBox} from "element-plus";
import 'element-plus/theme-chalk/el-message-box.css'


const activeName = ref('phone')
//1.表单对象
const phoneRegisterForm = ref(({
  phone: '',
  verCode: '',
  agree: true,
}))

const checkAgree = (rule, value, callback) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请勾选协议'))
  }
}

const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
// 验证手机号的规则
const checkMobile = (rule, value, callback) => {
  // 验证手机号的正则表达式
  if (regMobile.test(value)) {
    return callback()
  }
  callback(new Error('请输入合法的手机号'))
}

const phoneRegisterFormRules = {
  phone: [{
    required: true,
    message: '请输入你的手机号',
    trigger: 'blur'
  },
    [{min: 11, max: 11, message: '手机号为11位', trigger: 'blur'}],
    {
      validator: checkMobile,
      trigger: 'blur'
    }
  ],
  verCode: [{
    required: true,
    message: '请输入你获取到的验证码',
    trigger: 'blur'
  }],
  agree: [
    {
      validator: checkAgree
    }
  ]
}
const phoneRegisterFormRef = ref(null);
const doRegister= () => {
  phoneRegisterFormRef.value.validate(async (valid) => {
    if(valid) {
      const {phone, verCode} = phoneRegisterForm.value
      const res = await userRegisterAPI({phone, verCode})
      registerData(res.data)
    }
  })
}

const registerData = (res) => {
  console.log("res",res)
  //登录跳转逻辑
  if (res) {
    ElMessageBox.alert('您的账号为：'+res+'，密码默认为注册手机号码，登录后请尽快修改!' ,'注册成功')
    router.replace("/login")
  }
}

/**
 * 倒计时
 */
const handleTimeChange = () => {
  if (time.value <= 0) {
    isDisposed.value = false;
    time.value = 60;
  } else {
    setTimeout(() => {
      time.value--;
      handleTimeChange();
    }, 1000);
  }
};

const time = ref(60);
const isDisposed = ref(false);

/**
 * 发送验证码
 * @returns {Promise<void>}
 */
const sendCode = async () => {
  //const loginAdapter = activeName.value
  const {phone} = phoneRegisterForm.value
  if (regMobile.test(phone)) {
    // 校验该表单项，如果不通过重新显示校验结果
    const res = await sendPhoneCodeAPI({phone});
    //console.log(res)
    isDisposed.value = true;
    handleTimeChange()
  } else {
    ElMessage.error('请输入正确的手机号！')
  }
}


/**
 * 登录跳转接口
 */
const toLogin = () => {
  router.push({
    path: '/login'
  })
}

</script>


<template>
  <div>
    <header class="login-header">
      <div class="container m-top-20">
        <h1 class="logo">
          <RouterLink to="/">Y-mall商城</RouterLink>
        </h1>
        <RouterLink class="entry" to="/">
          进入网站首页
          <i class="iconfont icon-angle-right"></i>
          <i class="iconfont icon-angle-right"></i>
        </RouterLink>
      </div>
    </header>
    <section class="login-section">
      <div class="wrapper">
        <el-tabs class="account-box" v-model="activeName">
          <el-tab-pane name="phone" style="margin-top: 15px">
            <template #label>
              <div style="padding: 20px;font-size: 17px;font-weight: 500;display: inline-block;">
                注册
              </div>
            </template>
            <div class="form">
              <el-form label-position="right" label-width="80px"
                       status-icon :rules="phoneRegisterFormRules" :model="phoneRegisterForm" ref="phoneRegisterFormRef">
                <el-form-item prop="phone" label="手机号">
                  <el-input placeholder="手机号" v-model="phoneRegisterForm.phone">
                  </el-input>
                </el-form-item>
                <!-- 邮箱验证码 -->
                <el-form-item prop="verCode" label="验证码">
                  <el-input placeholder="验证码" v-model="phoneRegisterForm.verCode">
                    <template #append>
                      <el-button @click="sendCode" :disabled="isDisposed">
                        {{ isDisposed ? `${time}s后重新获取` : "获取验证码" }}
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-button size="large" class="subBtn" @click="doRegister">注册</el-button>
                <el-form-item label-width="10px" prop="agree" style="margin-top: 15px">
                  <el-checkbox size="large" v-model="phoneRegisterForm.agree">
                    我已同意隐私条款和服务条款
                  </el-checkbox>
                  <el-button @click='toLogin' class="register_btn">去登录</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

    </section>

    <footer class="login-footer">
      <div class="container">
        <p>
          <a href="javascript:;">关于我们</a>
          <a href="javascript:;">帮助中心</a>
          <a href="javascript:;">售后服务</a>
          <a href="javascript:;">配送与验收</a>
          <a href="javascript:;">商务合作</a>
          <a href="javascript:;">搜索推荐</a>
          <a href="javascript:;">友情链接</a>
        </p>
        <p>CopyRight &copy; Y-mall商城</p>
      </div>
    </footer>
  </div>
</template>

<style scoped lang='scss'>
.register_btn {
  position: absolute;
  right: 10px;
  border: none

}

.login-header {
  background: #fff;
  border-bottom: 1px solid #e4e4e4;

  .container {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
  }

  .logo {
    width: 200px;

    a {
      display: block;
      height: 132px;
      width: 100%;
      text-indent: -9999px;
      background: url("@/assets/images/logo.png") no-repeat center 18px / contain;
    }
  }

  .sub {
    flex: 1;
    font-size: 24px;
    font-weight: normal;
    margin-bottom: 38px;
    margin-left: 20px;
    color: #666;
  }

  .entry {
    width: 120px;
    margin-bottom: 38px;
    font-size: 16px;

    i {
      font-size: 14px;
      color: $xtxColor;
      letter-spacing: -5px;
    }
  }
}

.login-section {
  background: url('@/assets/images/login-bg.png') no-repeat center / cover;
  height: 488px;
  position: relative;

  .wrapper {
    width: 380px;
    background: #fff;
    position: absolute;
    left: 50%;
    top: 54px;
    transform: translate3d(100px, 0, 0);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
  }
}

.login-footer {
  padding: 30px 0 50px;
  background: #fff;

  p {
    text-align: center;
    color: #999;
    padding-top: 20px;

    a {
      line-height: 1;
      padding: 0 10px;
      color: #999;
      display: inline-block;

      ~ a {
        border-left: 1px solid #ccc;
      }
    }
  }
}

.account-box {
  margin-top: 20px;

  .toggle {
    padding: 15px 40px;
    text-align: right;

    a {
      color: $xtxColor;

      i {
        font-size: 14px;
      }
    }
  }

  .form {
    padding: 0 20px 20px 20px;

    &-item {
      margin-bottom: 28px;

      .input {
        position: relative;
        height: 36px;

        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }

        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;

          &.error {
            border-color: $priceColor;
          }

          &.active,
          &:focus {
            border-color: $xtxColor;
          }
        }

        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }

      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: $priceColor;

        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      a {
        color: #069;
      }
    }

    .btn {
      display: block;
      width: 100%;
      height: 480px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: $xtxColor;

      &.disabled {
        background: #cfcdcd;
      }
    }
  }

  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}

.subBtn {
  background: $xtxColor;
  width: 100%;
  color: #fff;
  font-size: 18px;
}
</style>